package org.jeecg.modules.product.riskUnit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.product.riskUnit.entity.TbBaseRiskDevice;
import org.jeecg.modules.product.riskUnit.entity.TbBaseRiskUnit;
import org.jeecg.modules.product.riskUnit.service.ITbBaseRiskDeviceService;
import org.jeecg.modules.product.riskUnit.service.ITbBaseRiskUnitService;
import org.jeecg.modules.product.riskUnit.vo.TbBaseRiskDevicePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 重大危险源装置
 * @Author: jeecg-boot
 * @Date:   2024-04-16
 * @Version: V1.0
 */
@Tag(name="重大危险源装置")
@RestController
@RequestMapping("/TbBaseRiskDevice/tbBaseRiskDevice")
@Slf4j
public class TbBaseRiskDeviceController {
	@Autowired
	private ITbBaseRiskDeviceService tbBaseRiskDeviceService;
	@Autowired
	private ITbBaseRiskUnitService tbBaseRiskUnitService;
	
	/**
	 * 分页列表查询
	 *
	 * @param tbBaseRiskDevice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "重大危险源装置-分页列表查询")
	@Operation(summary="重大危险源装置-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TbBaseRiskDevice>> queryPageList(TbBaseRiskDevice tbBaseRiskDevice,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		QueryWrapper<TbBaseRiskDevice> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskDevice, req.getParameterMap());
		Page<TbBaseRiskDevice> page = new Page<TbBaseRiskDevice>(pageNo, pageSize);
		IPage<TbBaseRiskDevice> pageList = tbBaseRiskDeviceService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tbBaseRiskDevicePage
	 * @return
	 */
	@AutoLog(value = "重大危险源装置-添加")
	@Operation(summary="重大危险源装置-添加")
    //@RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TbBaseRiskDevicePage tbBaseRiskDevicePage) {
		TbBaseRiskDevice tbBaseRiskDevice = new TbBaseRiskDevice();
		BeanUtils.copyProperties(tbBaseRiskDevicePage, tbBaseRiskDevice);
		tbBaseRiskDeviceService.saveMain(tbBaseRiskDevice, tbBaseRiskDevicePage.getTbBaseRiskUnitList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tbBaseRiskDevicePage
	 * @return
	 */
	@AutoLog(value = "重大危险源装置-编辑")
	@Operation(summary="重大危险源装置-编辑")
    //@RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TbBaseRiskDevicePage tbBaseRiskDevicePage) {
		TbBaseRiskDevice tbBaseRiskDevice = new TbBaseRiskDevice();
		BeanUtils.copyProperties(tbBaseRiskDevicePage, tbBaseRiskDevice);
		TbBaseRiskDevice tbBaseRiskDeviceEntity = tbBaseRiskDeviceService.getById(tbBaseRiskDevice.getId());
		if(tbBaseRiskDeviceEntity==null) {
			return Result.error("未找到对应数据");
		}
		tbBaseRiskDeviceService.updateMain(tbBaseRiskDevice, tbBaseRiskDevicePage.getTbBaseRiskUnitList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "重大危险源装置-通过id删除")
	@Operation(summary="重大危险源装置-通过id删除")
    //@RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseRiskDeviceService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "重大危险源装置-批量删除")
	@Operation(summary="重大危险源装置-批量删除")
    //@RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseRiskDeviceService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "重大危险源装置-通过id查询")
	@Operation(summary="重大危险源装置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TbBaseRiskDevice> queryById(@RequestParam(name="id",required=true) String id) {
		TbBaseRiskDevice tbBaseRiskDevice = tbBaseRiskDeviceService.getById(id);
		if(tbBaseRiskDevice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbBaseRiskDevice);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "风险分析单元通过主表ID查询")
	@Operation(summary="风险分析单元主表ID查询")
	@GetMapping(value = "/queryTbBaseRiskUnitByMainId")
	public Result<List<TbBaseRiskUnit>> queryTbBaseRiskUnitListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TbBaseRiskUnit> tbBaseRiskUnitList = tbBaseRiskUnitService.selectByMainId(id);
		return Result.OK(tbBaseRiskUnitList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbBaseRiskDevice
    */
    @RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbBaseRiskDevice tbBaseRiskDevice) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<TbBaseRiskDevice> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskDevice, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<TbBaseRiskDevice> tbBaseRiskDeviceList = tbBaseRiskDeviceService.list(queryWrapper);

      // Step.3 组装pageList
      List<TbBaseRiskDevicePage> pageList = new ArrayList<TbBaseRiskDevicePage>();
      for (TbBaseRiskDevice main : tbBaseRiskDeviceList) {
          TbBaseRiskDevicePage vo = new TbBaseRiskDevicePage();
          BeanUtils.copyProperties(main, vo);
          List<TbBaseRiskUnit> tbBaseRiskUnitList = tbBaseRiskUnitService.selectByMainId(main.getId());
          vo.setTbBaseRiskUnitList(tbBaseRiskUnitList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "重大危险源装置列表");
      mv.addObject(NormalExcelConstants.CLASS, TbBaseRiskDevicePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("重大危险源装置数据", "导出人:"+sysUser.getRealname(), "重大危险源装置"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("TbBaseRiskDevice:tb_base_risk_device:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<TbBaseRiskDevicePage> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseRiskDevicePage.class, params);
              for (TbBaseRiskDevicePage page : list) {
                  TbBaseRiskDevice po = new TbBaseRiskDevice();
                  BeanUtils.copyProperties(page, po);
                  tbBaseRiskDeviceService.saveMain(po, page.getTbBaseRiskUnitList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /*--------------------------------子表处理-风险分析单元-begin----------------------------------------------*/
	 /**
	  * 通过主表ID查询
	  * @return
	  */
	 //@AutoLog(value = "风险分析单元-通过主表ID查询")
	 @Operation(summary="风险分析单元-通过主表ID查询")
	 @GetMapping(value = "/listTbBaseRiskUnitByMainId")
	 public Result<IPage<TbBaseRiskUnit>> listTbBaseRiskUnitByMainId(TbBaseRiskUnit tbBaseRiskUnit,
																	 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																	 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
																	 HttpServletRequest req) {
		 QueryWrapper<TbBaseRiskUnit> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskUnit, req.getParameterMap());
		 Page<TbBaseRiskUnit> page = new Page<TbBaseRiskUnit>(pageNo, pageSize);
		 IPage<TbBaseRiskUnit> pageList = tbBaseRiskUnitService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 添加
	  * @param tbBaseRiskUnit
	  * @return
	  */
	 @AutoLog(value = "风险分析单元-添加")
	 @Operation(summary="风险分析单元-添加")
	 @PostMapping(value = "/addTbBaseRiskUnit")
	 public Result<String> addTbBaseRiskUnit(@RequestBody TbBaseRiskUnit tbBaseRiskUnit) {
		 tbBaseRiskUnitService.save(tbBaseRiskUnit);
		 return Result.OK("添加成功！");
	 }

	 /**
	  * 编辑
	  * @param tbBaseRiskUnit
	  * @return
	  */
	 @AutoLog(value = "风险分析单元-编辑")
	 @Operation(summary="风险分析单元-编辑")
	 @RequestMapping(value = "/editTbBaseRiskUnit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editTbBaseRiskUnit(@RequestBody TbBaseRiskUnit tbBaseRiskUnit) {
		 tbBaseRiskUnitService.updateById(tbBaseRiskUnit);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  * 通过id删除
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "风险分析单元-通过id删除")
	 @Operation(summary="风险分析单元-通过id删除")
	 @DeleteMapping(value = "/deleteTbBaseRiskUnit")
	 public Result<String> deleteTbBaseRiskUnit(@RequestParam(name="id",required=true) String id) {
		 tbBaseRiskUnitService.removeById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 批量删除
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "风险分析单元-批量删除")
	 @Operation(summary="风险分析单元-批量删除")
	 @DeleteMapping(value = "/deleteBatchTbBaseRiskUnit")
	 public Result<String> deleteBatchTbBaseRiskUnit(@RequestParam(name="ids",required=true) String ids) {
		 this.tbBaseRiskUnitService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功!");
	 }

	 /**
	  * 导出
	  * @return
	  */
	 @RequestMapping(value = "/exportTbBaseRiskUnit")
	 public ModelAndView exportTbBaseRiskUnit(HttpServletRequest request, TbBaseRiskUnit tbBaseRiskUnit) {
		 // Step.1 组装查询条件
		 QueryWrapper<TbBaseRiskUnit> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskUnit, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<TbBaseRiskUnit> pageList = tbBaseRiskUnitService.list(queryWrapper);
		 List<TbBaseRiskUnit> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "风险分析单元");
		 mv.addObject(NormalExcelConstants.CLASS, TbBaseRiskUnit.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("风险分析单元报表", "导出人:" + sysUser.getRealname(), "风险分析单元"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }

	 /**
	  * 导入
	  * @return
	  */
	 @RequestMapping(value = "/importTbBaseRiskUnit/{mainId}")
	 public Result<?> importTbBaseRiskUnit(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<TbBaseRiskUnit> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseRiskUnit.class, params);
				 for (TbBaseRiskUnit temp : list) {
					 temp.setDeviceId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 tbBaseRiskUnitService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

	 /*--------------------------------子表处理-风险分析单元-end----------------------------------------------*/

}
